package com.lmx.message;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.MessageService;
import com.lmx.repoDomain.tmodel.Message;
import com.lmx.repoDomain.tmodel.business.User;

/**
 * 
 * 
 * @author huibati
 * @version 1.00
 */
@Service
@Scope("prototype")
public class SendMessageService<T> {

	private Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	protected MessageService messageService;

	public void serviceExecute() {
		// 开启线程，执行操作
		ExecutorService poolMsg = Executors.newFixedThreadPool(3);// 消息发送进程
		ExecutorService poolWarningMsg = Executors.newFixedThreadPool(3);// 预警消息发送进程
		for (int i = 0; i < 3; i++) {
			poolMsg.execute(new SendMessage(ActionContextHolder.getMessageQueue(), i + ""));
		}
		for (int i = 0; i < 3; i++) {
			poolWarningMsg.execute(new SendWarningMessage(ActionContextHolder.getMessageQueue(), i + ""));
		}
	}

	private class SendMessage implements Runnable {
		// 同步队列类变量
		private MessageQueue queue;

		private String remark;

		// 该构造函数初始化同步队列类变量
		public SendMessage(MessageQueue queue, String remark) {
			this.queue = queue;
			this.remark = remark;
		}

		// 线程运行主体
		public void run() {
			while (true) {
				try {
					Thread.sleep(CommonUtil.randomInt(5, 1) * 1000); 
				} catch (Exception e) {
					logger.debug("sendMessage error  " + e);
				}
				
				Message data = queue.popMessage();// 发送消息
				if (data != null) {
					for (User user : data.getUserList()) {
						if (user != null) {
							data.setToUser(user);
							data.setFromUser(user);
							logger.debug("sendMessage to uid: " + user.getId());
							messageService.sendMessage(data, user.getId());
						}
					}
				}

			}
		}
	}

	private class SendWarningMessage implements Runnable {
		// 同步队列类变量
		private MessageQueue queue;

		private String remark;

		// 该构造函数初始化同步队列类变量
		public SendWarningMessage(MessageQueue queue, String remark) {
			this.queue = queue;
			this.remark = remark;
		}

		// 线程运行主体
		public void run() {
			while (true) {
				try {
					Thread.sleep(2000);
				} catch (Exception e) {
					logger.debug("sendWarningMsg error  " + e);
				}
				
				Message data = queue.popWarningMsg();// 发送消息
				if (data != null) {
					for (User user : data.getUserList()) {
						if (user != null) {
							data.setToUser(user);
							data.setFromUser(user);
							logger.debug("sendWarningMsg to uid: " + user.getId());
							messageService.sendMessage(data, user.getId());
						}
					}
				}

				
			}
		}
	}

}
